﻿using Microsoft.AspNetCore.Mvc;
using XKPlatform.DataModels;
using XKPlatform.DataModels.ReturnModel;
using XKPlatform.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using XKPlatform.Common.Enums;

namespace XKPlatform.Service
{
    public class AuthenService
    {
        #region 用户角色变更
        /// <summary>
        /// 用户角色变更
        /// </summary>
        /// <param name="SaveTypeCode">类型</param>
        /// <param name="StrUserID">用户ID</param>
        /// <param name="RolesID">角色ID</param>
        /// <returns></returns>
        public ResultModel GetResultModel(string sysToken, string SaveTypeCode, string StrUserID, string RolesID)
        {
            MsgCodeEnum ErrType_Run = MsgCodeEnum.Failed;
            string StrSql = "";
            ResultModel RtnVal = new ResultModel();
            JObject RtnData = new JObject();
            JArray RtnData_Array = new JArray();
            DataSet ds = new DataSet();
            if (SSOClient.SYSToken == sysToken)//(new AuthenHelper().LoadSourseSetByToken().sysToken == sysToken)
            {
                try
                {
                    switch (SaveTypeCode)
                    {
                        case "1":
                            #region 新增角色
                            StrSql = "  insert into SysUser(UserID,UserNo,DefaultRoleID,CreatedOn,RecordStatus) values((select NEWID()),@AccountID,@RoleId,GETDATE(),0) ";
                            if (SqlHelper.ExecuteSql(StrSql,
                                              new SqlParameter[]
                                                  {
                                                 new SqlParameter("@AccountID", StrUserID),
                                                 new SqlParameter("@RoleId", RolesID)
                                                  }) != 1) { throw new Exception(""); };
                            #endregion
                            break;
                        case "2":
                            #region 修改角色
                            StrSql = " Delete SysUser Where UserNo=@AccountID";
                            if (SqlHelper.ExecuteSql(StrSql,
                                             new SqlParameter[]
                                                 {
                                                 new SqlParameter("@AccountID", StrUserID)
                                                 }) != 1) { throw new Exception(""); };
                            StrSql = " insert into SysUser(UserID,UserNo,DefaultRoleID,CreatedOn,RecordStatus) values((select NEWID()),@AccountID,@RoleId,GETDATE(),0)  ";
                            if (SqlHelper.ExecuteSql(StrSql,
                                              new SqlParameter[]
                                                  {
                                                 new SqlParameter("@AccountID", StrUserID),
                                                 new SqlParameter("@RoleId", RolesID)
                                                  }) != 1) { throw new Exception(""); };
                            #endregion
                            break;

                    }
                    ErrType_Run = MsgCodeEnum.Success;
                }
                catch (Exception ErrInfo)
                {
                    RtnData = null;
                    RtnData_Array = null;
                    string ErrMsg = ErrInfo.Message.ToString();
                    if (ErrMsg != MsgCodeEnum.InvalidParameter.ToString())
                    {
                        ErrType_Run = MsgCodeEnum.ReadDataError;
                    }
                }
            }
            else
            {
                ErrType_Run = MsgCodeEnum.Authen_SysToken;
                RtnData = null;
                RtnData_Array = null;
            }
            MsgInfo msg = EnumUtils.GetEnumDescAll(ErrType_Run);
            RtnVal.errCode = ((int)ErrType_Run).ToString();
            RtnVal.message = msg.Cn;
            RtnVal.data = RtnData;
            RtnVal.list = RtnData_Array;

            return RtnVal;

        }
        #endregion


        /// <summary>
        /// 获取系统角色
        /// </summary>
        /// <param name="sysToken">系统Token</param>
        /// <returns></returns>
        public ResultModel GetRoleList(string sysToken)
        {
            MsgCodeEnum ErrType_Run = MsgCodeEnum.Failed;
            string StrSql = "";
            ResultModel RtnVal = new ResultModel();
            JObject RtnData = new JObject();
            JArray RtnData_Array = new JArray();
            try
            {
                if (SSOClient.SYSToken == sysToken)//(new AuthenHelper().LoadSourseSetByToken().sysToken == sysToken)
                {
                    QuerySuite querySuite = new QuerySuite("SysRole");

                    StrSql = "select RoleID as Id,RoleName as Name from SysRole where  RecordStatus=0   order by RoleName";

                    DataSet ds = SqlHelper.Query(StrSql);
                    //RtnData_Array = ResultHelper.DataTableToJArray(ds.Tables[0]);
                    RtnData_Array = JArray.Parse(Common.Extends.StringExtension.ToJson(ds.Tables[0]));
                    RtnData = null;
                    ErrType_Run = MsgCodeEnum.Success;
                }
                else
                {
                    RtnData_Array = null;
                    RtnData = null;
                    ErrType_Run = MsgCodeEnum.Authen_SysToken;
                }
            }
            catch (Exception ec)
            {
                RtnData = null;
                RtnData_Array = null;
                string ErrMsg = ec.Message.ToString();
                if (ErrMsg != MsgCodeEnum.Authen_SysToken.ToString()) { ErrType_Run = MsgCodeEnum.Authen_SysToken; }
                if (ErrType_Run == MsgCodeEnum.Failed) { ErrType_Run = MsgCodeEnum.ReadDataError; }
            }
            MsgInfo msg = EnumUtils.GetEnumDescAll(ErrType_Run);
            RtnVal.errCode = ((int)ErrType_Run).ToString();
            RtnVal.message = msg.En;
            RtnVal.data = RtnData;
            RtnVal.list = RtnData_Array;

            return RtnVal;
        }

        /// <summary>
        /// 刷新系统Token
        /// </summary>
        /// <param name="sysToken"></param>
        /// <returns></returns>
        //public ResultModel refTokenInfo(string sysToken)
        //{
        //    MsgCodeEnum ErrType_Run = MsgCodeEnum.Failed;
        //    ResultModel RtnVal = new ResultModel();
        //    JObject RtnData = new JObject();
        //    JArray RtnData_Array = new JArray();
        //    try
        //    {
        //        sysTokenModel model = new sysTokenModel();
        //        //token赋值到全局变量中   
        //        if (!string.IsNullOrEmpty(sysToken))
        //        {
        //            model.sysToken = sysToken;
        //            new AuthenHelper().WriteSourseSetsToken(model);
        //        }

        //        RtnData_Array = null;
        //        RtnData = null;
        //        ErrType_Run = MsgCodeEnum.Success;

        //    }
        //    catch (Exception ErrInfo)
        //    {
        //        RtnData = null;
        //        RtnData_Array = null;
        //        string ErrMsg = ErrInfo.Message.ToString();
        //        if (ErrMsg != MsgCodeEnum.User_TokenCheck.ToString()) { ErrType_Run = MsgCodeEnum.User_TokenCheck; }
        //        if (ErrType_Run == MsgCodeEnum.Failed) { ErrType_Run = MsgCodeEnum.ReadDataError; }
        //    }
        //    //RtnVal = ResultHelper.GetRtnJson(ErrType_Run, "", "", RtnData, RtnData_Array);
        //    MsgInfo msg = EnumUtils.GetEnumDescAll(ErrType_Run);
        //    RtnVal.errCode = ((int)ErrType_Run).ToString();
        //    RtnVal.message = msg.En;
        //    RtnVal.data = RtnData;
        //    RtnVal.list = RtnData_Array;

        //    return RtnVal;
        //}

        /// <summary>
        /// 根据AccessToken请求认证中心，拿到用户信息
        /// </summary>
        /// <param name="Token"></param>
        /// <returns></returns>
        public string GetUserInfo(string Token, int type = 0)
        {
            AuthenModel model = new AuthenModel();
            string url = "";


            //var ApiType = HttpContextCore.Configuration["AuthenApiUrl:ApiType"];
            //var ApiUrl = HttpContextCore.Configuration["AuthenApiUrl:ApiUrl"];
            //string ApiUrl = string.Empty;


            //string StrSql = "select * from Base_CertificationCenterSet where ParameterType in('ApiUrl')";
            //DataTable dt = SqlHelper.Query(StrSql).Tables[0];
            //if(dt.Rows.Count==1)
            //{
            //    ApiUrl = dt.Rows[0]["ParameterValue"].ToString();
            //}
            //else
            //{
            //    return "-1";
            //}

            if (!string.IsNullOrEmpty(Token))
            {
                url = SSOClient.ApiHost.TrimEnd('/') + "/" + "api/Power/CheckToken?strAccessToken=" + Token;

                string result = new ClientHelper().HttpsPostUserInfo(url);

                model = JsonConvert.DeserializeObject<AuthenModel>(result);
                if (model.ErrCode == "0")
                {
                    if (!string.IsNullOrEmpty(model.Data.UserID))
                    {
                        if (type == 0)
                        {
                            if (SSOClient.Validate(model.Data.UserID, out SysUser user))
                            {
                                user.UserName = model.Data.ChineseName;
                                user.Email = model.Data.Email;
                                user.UserNo = model.Data.LoginAccount;

                                return "0";
                            }
                        }
                        else
                        {
                            return "0";
                        }
                    }
                    else
                    {
                        return "-1";
                    }
                }
            }

            return "-1";

        }

        /// <summary>
        /// 获取认证中心的配置信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="type"></param>
        //public void GetAuthenUrl(out string url, out string type)
        //{
        //    string result = string.Empty;
        //    string StrSql = "  select ParameterValue from Base_CertificationCenterSet where ParameterType in('ApiType','ApiUrl')";
        //    DataTable dt = SqlHelper.Query(StrSql).Tables[0];
        //    if (dt.Rows.Count == 2)
        //    {
        //        type = dt.Rows[0]["ParameterValue"].ToString();
        //        url = dt.Rows[1]["ParameterValue"].ToString();
        //    }
        //    else
        //    {
        //        type = "";
        //        url = "";
        //    }
        //}


    }

    public class sysTokenModel
    {
        /// <summary>
        /// 系统token
        /// </summary>
        public string sysToken { get; set; }
    }

    public class AuthenHelper
    {
        /// <summary>
        /// 读取系统Token
        /// </summary>
        /// <param name="sysToken"></param>
        /// <returns></returns>
        //public sysTokenModel LoadSourseSetByToken(string sysToken = "SYSToken")
        //{
        //    string StrSql = "select ParameterValue from Base_CertificationCenterSet where ParameterType='SYSToken'";
        //    sysTokenModel baseSetModel = new sysTokenModel();
        //    baseSetModel.sysToken = SqlHelper.GetSingle(StrSql).ToString();
        //    return baseSetModel;
        //}

        //public void WriteSourseSetsToken(sysTokenModel sourseSet)
        //{
        //    string StrSql = "update Base_CertificationCenterSet set ParameterValue=@SYSToken where ParameterType='SYSToken'";
        //    SqlParameter parameter = new SqlParameter("@SYSToken", sourseSet.sysToken);
        //    int result = SqlHelper.ExecuteSql(StrSql, parameter);
        //}

    }

}
